// api/user_api/user_login_list.go
package user_api

import (
	"github.com/gin-gonic/gin"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
)

type UserLoginListRequest struct {
	Type int `json:"type" form:"type" binding:"required,oneof=1 2"`
}

type UserLoginListResponse struct {
	models.UserLoginModel
	UserNickname string `json:"userNickname,omitempty"`
	UserAvatar   string `json:"userAvatar,omitempty"`
}

func (UserApi) UserLoginListView(c *gin.Context) {

	var cr UserLoginListRequest
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}

	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.Claims)
	if cr.Type == 2 {
		if claims.IsAuth() {
			res.FailWithMsg(c, "权限错误")
			return
		}
	}
	var userLoginList = make([]models.UserLoginModel, 0)
	switch cr.Type {
	case 1:
		global.DB.Order("created_at desc").Find(&userLoginList,
			"user_id = ? and lose = ?", claims.UserID, false)
	case 2:
		global.DB.Order("created_at desc").Preload("UserModel").Find(&userLoginList,
			"lose = ?", false)
	}

	var list = make([]UserLoginListResponse, 0)
	for _, model := range userLoginList {
		list = append(list, UserLoginListResponse{
			UserLoginModel: model,
			UserNickname:   model.UserModel.Nickname,
			UserAvatar:     model.UserModel.Avatar,
		})
	}
	res.OkWithData(c, list)
}
